package cn.smbms.controller;

import cn.smbms.pojo.Page;
import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.impl.UserServiceImpl;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserServiceImpl userService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String userLogin(HttpSession session, @RequestParam String userCode, @RequestParam String userPassword){
        String userName = userService.userLogin(userCode,userPassword);
        if(userName!=null && userName.length()>0){
            session.setAttribute("userName",userName);
            return "frame";
        }else{
           //登录失败
            return "redirect:/user/exLogin";
        }
    }

    @RequestMapping("/exLogin")
    public void loginError(){
        throw new RuntimeException("您输入的账号或密码有误！请重新登录");

    }


    @RequestMapping("/queryAllUser")
    public String queryAllUser(@RequestParam(value = "pageNumber",defaultValue = "1")
                               String pageNumbers,HttpSession session,
                               @RequestParam(value = "userName",required = false) String userName,
                               @RequestParam(value = "userRole",required = false,defaultValue = "0") String userRole){
        int pageSize = 4;
        int beginIndex = (Integer.parseInt(pageNumbers)-1)*pageSize;
        List<User> list = userService.queryAll(userName,Integer.parseInt(userRole),beginIndex,pageSize);
        Map<String,Object> map = new HashMap<>();
        map.put("pageData",list);
        int totalRecode = userService.totalRecode(userName,Integer.parseInt(userRole));
        int totalPage = totalRecode%pageSize==0?totalRecode/pageSize:totalRecode/pageSize+1;
        map.put("totalPage",totalPage);
        map.put("pageNumber",pageNumbers);

        session.setAttribute("Page",map);
        return "userlist";
    }

    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session){
        //移除session中userName
        session.removeAttribute("userName");
        //销毁session对象
        session.invalidate();
        return "login";
    }

    @ResponseBody
    @RequestMapping("/checkUserCode")
    public void checkUserCodeAjax(@RequestParam("userCode") String userCode, HttpServletResponse resp) throws IOException {
        String userCodes = userService.checkUserCode(userCode);
        if(userCodes!=null && userCodes.length()>0){

            resp.getWriter().print(JSONArray.toJSONString("exists"));
        }else{
            resp.getWriter().print(JSONArray.toJSONString("Noexists"));
        }

    }

    /**
     * 通过aJax请求获取用户角色信息
     * @param response
     */
    @ResponseBody
    @RequestMapping("/showRoleName")
    public void showUserRole_aJax(HttpServletResponse response) throws IOException {
        List<Role> list = userService.showRoleNameInfo();
        response.getWriter().print(JSONArray.toJSON(list));
    }

    @RequestMapping("/queryById")
    public String showByIdUserInfo(@RequestParam String id,HttpSession session){
        List<User> list = userService.showByIdUserInfo(id);
        session.setAttribute("user",list);
        return "usermodify";
    }
    @RequestMapping("/updateById")
    public String updateByIdUserInfo(User user){
        int i = userService.updateByIdUserInfo(user);
        if(i>0){
            return "redirect:/user/queryAllUser";
        }
        return "error";
    }
    @RequestMapping("/upload.html")
    public String upload(HttpServletRequest req, String name, @RequestParam(value = "Image1",required = false)MultipartFile imageFile) throws IOException {
        //获取上传的文件名
        String fileName = imageFile.getOriginalFilename();
        //提供一个上传的文件的路径
        String filePath = req.getSession().getServletContext().getRealPath("/static/uploadFile1234");
         //获取上传文件的大小
        long fileSize = imageFile.getSize();
        File file = new File(filePath,fileName);
        //判断文件夹是否存在 不存在则创建
        if(!file.exists()){
          //创建文件夹
          boolean b = file.mkdirs();
          if(b){
              System.out.println(file.getPath()+"创建文件成功！");
          }
        }
        //将指定file写入指定路径中
        imageFile.transferTo(file);
        System.out.println("写入Ok!");

        return "";
    }
}
